What is causing Null Pointer Exception in the following code in java? [migrated]
Posted
by
Joe
on Super User
See other posts from Super User
or by Joe
Published on 2012-11-01T03:25:23Z
Indexed on
2012/11/01
5:06 UTC
Read the original article
Hit count: 436
java
|exceptions
When I run the following code I get Null Pointer Exception. I cannot figure out why that is happening. Need Help.
public class LinkedList<T> {
private Link head = null;
private int length = 0;
public T get(int index) {
return find(index).item;
}
public void set(int index, T item) {
find(index).item = item;
}
public int length() {
return length;
}
public void add(T item) {
Link<T> ptr = head;
if (ptr == null) {
// empty list so append to head
head = new Link<T>(item);
} else {
// non-empty list, so locate last link
while (ptr.next != null) {
ptr = ptr.next;
}
ptr.next = new Link<T>(item);
}
length++; // update length cache
}
// traverse list looking for link at index
private Link<T> find(int index) {
Link<T> ptr = head;
int i = 0;
while (i++ != index) {
if(ptr!=null) {
ptr = ptr.next;
}
}
return ptr;
}
private static class Link<S> {
public S item;
public Link<S> next;
public Link(S item) {
this.item = item;
}
}
public static void main(String[] args) {
new LinkedList<String>().get(1);
}
}
© Super User or respective owner